package com.flyduck.modules.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyduck.common.exception.BusinessException;
import com.flyduck.entity.AppProduct;
import com.flyduck.entity.AppSkuStock;
import com.flyduck.entity.AppSpecification;
import com.flyduck.entity.AppSpecificationValue;
import com.flyduck.mapper.AppProductMapper;
import com.flyduck.mapper.AppSkuStockMapper;
import com.flyduck.mapper.AppSpecificationMapper;
import com.flyduck.mapper.AppSpecificationValueMapper;
import com.flyduck.modules.admin.service.AdminSkuService;
import com.flyduck.modules.admin.vo.AdminSkuDetailsRespVO;
import com.flyduck.modules.admin.vo.AdminSkuSaveReqVO;
import com.flyduck.utils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * AdminSkuServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2024-06-06
 */
@Slf4j
@Service
public class AdminSkuServiceImpl implements AdminSkuService {

    @Resource
    private AppProductMapper appProductMapper;
    @Resource
    private AppSpecificationMapper appSpecificationMapper;
    @Resource
    private AppSpecificationValueMapper appSpecificationValueMapper;
    @Resource
    private AppSkuStockMapper appSkuStockMapper;

    @Override
    public AdminSkuDetailsRespVO getSkuDetailsByProductId(Long productId) {
        //商品信息
        AppProduct appProduct = appProductMapper.selectById(productId);
        if (appProduct == null) {
            throw new BusinessException("商品不存在");
        }

        //获取所有内置规格
        List<AppSpecification> appSpecificationList = appSpecificationMapper.selectList(
                new LambdaQueryWrapper<AppSpecification>()
        );

        //获取该商品对应的规格值
        List<AppSpecificationValue> appSpecificationValueList = appSpecificationValueMapper.selectList(
                new LambdaQueryWrapper<AppSpecificationValue>()
                        .eq(AppSpecificationValue::getProductId, productId)
        );

        //获取选中的规格值的名称组合
        List<String> selectSpecValues = appSpecificationValueList.stream()
                .map(AppSpecificationValue::getSpec)
                .collect(Collectors.toList());


        //获取该商品sku的信息
        List<AppSkuStock> appSkuStockList = appSkuStockMapper.selectList(
                new LambdaQueryWrapper<AppSkuStock>()
                        .eq(AppSkuStock::getProductId, productId)
        );

        AdminSkuDetailsRespVO adminSkuDetailsRespVO = new AdminSkuDetailsRespVO();

        AdminSkuDetailsRespVO.AppProductVO product = BeanUtils.toBean(appProduct, AdminSkuDetailsRespVO.AppProductVO.class);
        adminSkuDetailsRespVO.setProduct(product);

        List<AdminSkuDetailsRespVO.AppSpecificationVO> specs = BeanUtils.toBeanList(appSpecificationList, AdminSkuDetailsRespVO.AppSpecificationVO.class);
        adminSkuDetailsRespVO.setSpecs(specs);

        List<AdminSkuDetailsRespVO.AppSpecificationValueVO> specValues = BeanUtils.toBeanList(appSpecificationValueList, AdminSkuDetailsRespVO.AppSpecificationValueVO.class);
        adminSkuDetailsRespVO.setSpecValues(specValues);

        adminSkuDetailsRespVO.setSelectSpecValues(selectSpecValues);

        List<AdminSkuDetailsRespVO.AppSkuStockVO> skuStocks = BeanUtils.toBeanList(appSkuStockList, AdminSkuDetailsRespVO.AppSkuStockVO.class);
        adminSkuDetailsRespVO.setSkuStocks(skuStocks);
        return adminSkuDetailsRespVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSku(AdminSkuSaveReqVO adminSkuSaveReqVO) {
        //先删除原来的规格值，再保存商品规格值
        appSpecificationValueMapper.delete(
                new LambdaQueryWrapper<AppSpecificationValue>()
                .eq(AppSpecificationValue::getProductId,adminSkuSaveReqVO.getProductId())
        );

        List<AdminSkuSaveReqVO.AppSpecificationValueVO> specValues = adminSkuSaveReqVO.getSpecValues();
        if(CollectionUtil.isNotEmpty(specValues)){
            List<AppSpecificationValue> appSpecificationValues = BeanUtils.toBeanList(specValues, AppSpecificationValue.class);
            appSpecificationValues.forEach(appSpecificationValue -> {
                appSpecificationValue.setCreated(LocalDateTime.now());
            });
            appSpecificationValueMapper.insertBatch(appSpecificationValues);
        }else {
            log.info("规格为空，商品为单规格商品");
        }


        //不能直接删除原来的skuStock，因为购物车里面存储了skuId
        //先保存更新原来的，再删除多余的
        List<AdminSkuSaveReqVO.AppSkuStockVO> appSkuStockVOList = adminSkuSaveReqVO.getSkuStocks();
        if (CollectionUtil.isNotEmpty(appSkuStockVOList)) {
            List<AppSkuStock> appSkuStockList = BeanUtils.toBeanList(appSkuStockVOList, AppSkuStock.class);
            for (AppSkuStock appSkuStock : appSkuStockList) {
                if (appSkuStock.getId() == null) {
                    appSkuStock.setCreated(LocalDateTime.now());
                }else {
                    appSkuStock.setUpdated(LocalDateTime.now());
                }
            }
            appSkuStockMapper.insertOrUpdateBatch(appSkuStockList);
        }

        Set<Long> existSkuIds = appSkuStockVOList.stream()
                .map(AdminSkuSaveReqVO.AppSkuStockVO::getId)
                .collect(Collectors.toSet());
        appSkuStockMapper.delete(
                new LambdaQueryWrapper<AppSkuStock>()
                .eq(AppSkuStock::getProductId,adminSkuSaveReqVO.getProductId())
                .notIn(AppSkuStock::getId,existSkuIds)
        );
    }
}
